package com.ysu.demo.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ysu.demo.Local.MyLocal;
import com.ysu.demo.annotation.PassToken;
import com.ysu.demo.annotation.UserToken;
import com.ysu.demo.dto.UserDTOToken;
import com.ysu.demo.enums.ExceptionEnum;
import com.ysu.demo.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author ：lhw
 * @date ：Created in 2019/9/8 11:12
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token"); //获取请求头token
        response.setCharacterEncoding("utf-8"); //防止乱码
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Method method = handlerMethod.getMethod();

            //不需要的直接通过
            if(method.isAnnotationPresent(PassToken.class)){
                return true;
            }

            //检查头是否存在token
            if(StringUtils.isEmpty(token)){
                throw new BaseException(ExceptionEnum.NOT_PASS);
            }

            //检查token是否存在
            if(!stringRedisTemplate.hasKey(token)){
                throw new BaseException(ExceptionEnum.NOT_PASS);
            }

            //获取实际token内容
            String loginString = stringRedisTemplate.opsForValue().get(token);
            UserDTOToken userDTOToken = objectMapper.readValue(loginString,UserDTOToken.class);
            //System.out.println(userDTOToken);

            //判断权限
            Integer power = 2;
            if(method.isAnnotationPresent(UserToken.class)){
                power = 1;
            }

            if(userDTOToken.getPower() < power){
                throw new BaseException(ExceptionEnum.NOT_PASS);
            }

            //设置存储
            if(power.equals(1)){
                try{
                    MyLocal.addId(userDTOToken.getCollege().getId());
                }catch (NullPointerException e) {

                }
            }
        }
        return true;
    }
}
